package com.toocms.jinjuhang.ui.mine.order.confirm

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.core.graphics.drawable.DrawableCompat
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ResourceUtils
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.AddressDetailsData
import com.toocms.jinjuhang.data.flow.ConfirmOrderData
import com.toocms.jinjuhang.data.flow.SubmitOrderData
import com.toocms.jinjuhang.ui.mine.order.OrderServiceItemModel
import com.toocms.jinjuhang.ui.mine.payment.PaymentFgt
import com.toocms.jinjuhang.ui.mine.receiver_address.ReceiverAddressFgt
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger

class ConfirmOrderModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {

    val cartIds by lazy {
        bundle?.getString(Constants.BundleKey.KEY_CART_IDS)
    }

    val goodsId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_GOODS_ID)
    }

    val quantity by lazy {
        bundle?.getString(Constants.BundleKey.KEY_QUANTITY)
    }

    val goodsAttrIds by lazy {
        bundle?.getString(Constants.BundleKey.KEY_GOODS_ATTR_IDS)
    }

    val goodsAttrDesc by lazy {
        bundle?.getString(Constants.BundleKey.KEY_GOODS_ATTR_DESC)
    }

    var adrId: String? = null

    val backObservableField by lazy {
        val content = ResourceUtils.getDrawable(R.mipmap.icon_arrow_left_black).mutate()
        DrawableCompat.setTint(content, 0xFFFFFFFF.toInt())
        ObservableField(content)
    }
    val backClickBindingCommand = BindingCommand<BindingAction>(this::finishFragment)

    val dataObservableField = ObservableField<ConfirmOrderData>()
    val remarkObservableField = ObservableField<String>()

    val serviceItems = ObservableArrayList<OrderServiceItemModel>()
    val serviceItemBinding =
        ItemBinding.of<OrderServiceItemModel>(BR.orderServiceItemModel, R.layout.item_order_service)

    val addressClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val bundle = Bundle()
        bundle.putString(Constants.BundleKey.KEY_ACTION, Constants.Extra.ACTION_ACQUIRE)
        startFragment(ReceiverAddressFgt::class.java, bundle)
    })

    val paymentClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
//        startFragment(PaymentResultFgt::class.java)
        submit()
    })

    init {
        initializeMessenger()
        requestData()
    }

    private fun initializeMessenger() {
        Messenger.getDefault().register(
            this, Constants.MessengerToken.TOKEN_ADDRESS, AddressDetailsData::class.java
        ) {
            adrId = it?.adr_id ?: ""
            requestData()
        }
    }

    private fun requestData() {
        var url = ""
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["adr_id"] = adrId
        if (!TextUtils.isEmpty(goodsId)) {
            url = Urls.Flow.FAST_CONFIRM_ORDER
            params["goods_id"] = goodsId
            params["quantity"] = quantity
            params["goods_attr_ids"] = goodsAttrIds
            params["goods_attr_desc"] = goodsAttrDesc
        } else {
            url = Urls.Flow.CONFIRM_ORDER
            params["cart_ids"] = cartIds
        }
        requestData(url, params, resultClass = ConfirmOrderData::class.java, result = {
            adrId = it.address?.adr_id ?: ""
            dataObservableField.set(it)
            serviceItems.clear()
            it.goods_list?.forEach {
                serviceItems += OrderServiceItemModel(this, ObservableField(it))
            }
        })
    }

    private fun submit() {
        var url = ""
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["adr_id"] = adrId
        params["remark"] = remarkObservableField.get()
        if (!TextUtils.isEmpty(goodsId)) {
            url = Urls.Flow.FAST_SUBMIT_ORDER
            params["goods_id"] = goodsId
            params["quantity"] = quantity
            params["goods_attr_ids"] = goodsAttrIds
        } else {
            url = Urls.Flow.SUBMIT_ORDER
            params["cart_ids"] = cartIds
        }
        requestData(url, params, resultClass = SubmitOrderData::class.java, result = {
            Messenger.getDefault().sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_CART)
            if (0f >= it.pay_amounts?.toFloat()?:0f || Constants.Extra.ORDER_TYPE_INTEGRAL == dataObservableField.get()?.order_type) {
                showToast(R.string.str_order_succeed_hint)
                finishFragment()
                return@requestData
            } else {
                val bundle = Bundle()
                bundle.putString(Constants.BundleKey.KEY_ORDER_SN, it.order_sn)
                bundle.putString(Constants.BundleKey.KEY_PAYMENT_SUM, it.pay_amounts)
                startFragment(PaymentFgt::class.java, bundle, true)
            }
        })
    }


}